package com.ihomey.linkuphome.ui;

import android.app.Activity;
import android.content.ClipData;
import android.content.ClipDescription;
import android.graphics.Point;
import android.graphics.PointF;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.DragEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.ihomey.linkuphome.DeviceController;
import com.ihomey.linkuphome.DividerItemDecoration;
import com.ihomey.linkuphome.DragShadowBuilder;
import com.ihomey.linkuphome.R;
import com.ihomey.linkuphome.WrapContentLinearLayoutManager;
import com.ihomey.linkuphome.adapter.AddedDeviceAdapter;
import com.ihomey.linkuphome.adapter.UnAddedDeviceAdapter;
import com.ihomey.linkuphome.base.BaseFragment;
import com.ihomey.linkuphome.entities.GroupDevice;
import com.ihomey.linkuphome.entities.SingleDevice;
import com.ihomey.linkuphome.listeners.GroupListener;
import com.ihomey.linkuphome.util.BindView;
import com.ihomey.linkuphome.widget.EmptyRecyclerView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/5/19.
 */

public class GroupSettingFragment extends BaseFragment implements GroupListener {

    @BindView(id = R.id.layout_devices_added)
    private LinearLayout layout_devices_added;
    @BindView(id = R.id.layout_devices_unadded)
    private LinearLayout layout_devices_unadded;
    @BindView(id = R.id.rcv_devices_added)
    private EmptyRecyclerView rcv_devices_added;
    @BindView(id = R.id.rcv_devices_unadded)
    private EmptyRecyclerView rcv_devices_unadded;
    @BindView(id = R.id.inc_empty_devices_added)
    private View inc_empty_devices_added;
    @BindView(id = R.id.inc_empty_devices_unadded)
    private View inc_empty_devices_unadded;
    @BindView(id = R.id.iv_group_type)
    private ImageView iv_group_type;
    @BindView(id = R.id.et_group_setting_name)
    private EditText et_group_setting_name;


    private final PointF dragTouchPointAdded = new PointF();
    private final PointF dragTouchPointUnAdded = new PointF();
    private Fragment mMainFragment;
    private DeviceController mController;
    private GroupDevice groupDevice;
    private int groupId;
    private AddedDeviceAdapter addedDeviceAdapter;
    private UnAddedDeviceAdapter unAddedDeviceAdapter;

    private boolean isAdd = true;
    private boolean isValidDrag = false;

    public static GroupSettingFragment newInstance(int groupId) {
        GroupSettingFragment fragment = new GroupSettingFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("groupId", groupId);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected View inflaterView(LayoutInflater inflater, ViewGroup container, Bundle bundle) {
        if (getArguments() != null) {
            groupId = getArguments().getInt("groupId");
        }
        return inflater.inflate(R.layout.fragment_group_setting, null);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mController = (DeviceController) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement DeviceController callback interface.");
        }
    }

    @Override
    public void initData() {
        super.initData();
        groupDevice = (GroupDevice) mController.getDevice(groupId);
    }

    @Override
    public void initWidget(View parentView) {
        super.initWidget(parentView);
        mMainFragment = this;
        if (mController.getDeviceType() == 1) {
            iv_group_type.setImageResource(R.drawable.lamp_lawn);
        } else if (mController.getDeviceType() == 2) {
            iv_group_type.setImageResource(R.drawable.lamp_rgb);
        }
        et_group_setting_name.setText(groupDevice.getName());
        et_group_setting_name.setSelection(groupDevice.getName().toString().length());
        et_group_setting_name.requestFocus();

        resetUI();
    }

    private void resetUI() {
        List<SingleDevice> boundedDevices = mController.getBoundedDevices(groupId);
        List<SingleDevice> unBoundedDevices = mController.getUnBoundedDevices(groupId);
        addedDeviceAdapter = new AddedDeviceAdapter(boundedDevices);
        unAddedDeviceAdapter = new UnAddedDeviceAdapter(unBoundedDevices);

        addedDeviceAdapter.setOnItemClickListener(new AddedDeviceAdapter.OnItemClickListener() {
            @Override
            public void onItemLongClick(View view, int position) {
                ClipData.Item item;
                String[] clipDescription = {ClipDescription.MIMETYPE_TEXT_PLAIN};
                ClipData dragData;
                Point point;
                SingleDevice singleDevice = addedDeviceAdapter.getItem(position);
                item = new ClipData.Item(singleDevice.getName());
                dragData = new ClipData((CharSequence) view.getTag(), clipDescription, item);
                point = new Point(((int) (dragTouchPointAdded.x - view.getX())), (int) (dragTouchPointAdded.y - view.getY()));
                View.DragShadowBuilder myShadow = new DragShadowBuilder(view, point);
                rcv_devices_added.startDrag(dragData, myShadow, singleDevice, 0);

            }
        });

        unAddedDeviceAdapter.setOnItemClickListener(new UnAddedDeviceAdapter.OnItemClickListener() {
            @Override
            public void onItemAdd(int position) {
                SingleDevice singleDevice = unAddedDeviceAdapter.getItem(position);
                boundDevice(singleDevice);
            }

            @Override
            public void onItemLongClick(View view, int position) {
                ClipData.Item item;
                String[] clipDescription = {ClipDescription.MIMETYPE_TEXT_PLAIN};
                ClipData dragData;
                Point point;
                SingleDevice singleDevice = unAddedDeviceAdapter.getItem(position);
                item = new ClipData.Item(singleDevice.getName());
                dragData = new ClipData((CharSequence) view.getTag(), clipDescription, item);
                point = new Point(((int) (dragTouchPointUnAdded.x - view.getX())), (int) (dragTouchPointUnAdded.y - view.getY()));
                View.DragShadowBuilder myShadow = new DragShadowBuilder(view, point);
                rcv_devices_unadded.startDrag(dragData, myShadow, singleDevice, 0);
            }
        });

        WrapContentLinearLayoutManager linearLayoutManager = new WrapContentLinearLayoutManager(rcv_devices_added.getContext());
        rcv_devices_added.setLayoutManager(linearLayoutManager);
        rcv_devices_added.setItemAnimator(new DefaultItemAnimator());
        rcv_devices_added.setAdapter(addedDeviceAdapter);
        rcv_devices_added.setEmptyView(inc_empty_devices_added);
        rcv_devices_added.addItemDecoration(new DividerItemDecoration(getContext(), linearLayoutManager.getOrientation(), true));

        rcv_devices_unadded.setLayoutManager(new WrapContentLinearLayoutManager(rcv_devices_unadded.getContext()));
        rcv_devices_unadded.setItemAnimator(new DefaultItemAnimator());
        rcv_devices_unadded.setAdapter(unAddedDeviceAdapter);
        rcv_devices_unadded.setEmptyView(inc_empty_devices_unadded);
        rcv_devices_unadded.addItemDecoration(new DividerItemDecoration(getContext(), linearLayoutManager.getOrientation(), unAddedDeviceAdapter.getItemCount() == 0 ? true : false));


        rcv_devices_added.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
            @Override
            public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
                isAdd = true;
                dragTouchPointAdded.set(e.getX(), e.getY());
                return false;
            }

            @Override
            public void onTouchEvent(RecyclerView rv, MotionEvent e) {

            }

            @Override
            public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

            }
        });
        rcv_devices_unadded.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
            @Override
            public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
                isAdd = false;
                dragTouchPointUnAdded.set(e.getX(), e.getY());
                return false;
            }

            @Override
            public void onTouchEvent(RecyclerView rv, MotionEvent e) {

            }

            @Override
            public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

            }
        });

        layout_devices_added.setOnDragListener(new View.OnDragListener() {
            @Override
            public boolean onDrag(View v, DragEvent event) {
                final int action = event.getAction();
                SingleDevice singleDevice = (SingleDevice) event.getLocalState();
                if (!isAdd) {
                    // 每个事件的处理
                    switch (action) {
                        case DragEvent.ACTION_DRAG_ENTERED:
                            isValidDrag = true;
                            return (true);
                        case DragEvent.ACTION_DRAG_EXITED:
                            isValidDrag = false;
                            return (true);
                        case DragEvent.ACTION_DRAG_ENDED:
                            if (isValidDrag) {
                                boundDevice(singleDevice);
//                                setDeviceGroups(true);
                                isValidDrag = false;
                            }
                            return (true);
                        default:
                            Log.e("DragDrop Example", "Unknown action type received by OnDragListener.");
                            break;
                    }
                }
                return (true);
            }
        });


        layout_devices_unadded.setOnDragListener(new View.OnDragListener() {
            @Override
            public boolean onDrag(View v, DragEvent event) {
                final int action = event.getAction();
                SingleDevice singleDevice = (SingleDevice) event.getLocalState();
                if (isAdd) {
                    // 每个事件的处理
                    switch (action) {
                        case DragEvent.ACTION_DRAG_ENTERED:
                            isValidDrag = true;
                            return (true);
                        case DragEvent.ACTION_DRAG_EXITED:
                            isValidDrag = false;
                            return (true);
                        case DragEvent.ACTION_DRAG_ENDED:
                            if (isValidDrag) {
                                unBoundDevice(singleDevice);
                                isValidDrag = false;
                            }
                            return (true);
                        default:
                            Log.e("DragDrop Example", "Unknown action type received by OnDragListener.");
                            break;
                    }
                }
                return (true);
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (!TextUtils.equals(et_group_setting_name.getText().toString().trim(), groupDevice.getName().trim())) {
            mController.updateDeviceName(groupDevice.getDeviceId(), et_group_setting_name.getText().toString().trim());
        }
        InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(getActivity().INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(et_group_setting_name.getWindowToken(), 0);
    }

    private void boundDevice(SingleDevice singleDevice) {
        MainActivity mainActivity = (MainActivity) getActivity();
        mainActivity.showProgressDialog(getString(R.string.group_device_adding) + singleDevice.getName());
        List<Integer> groups = new ArrayList<>();
        groups.addAll(singleDevice.getGroupMembership());
        groups.add(groupId);
        mController.setSelectedDeviceId(singleDevice.getDeviceId());
        mController.setDeviceGroups(groups, (GroupListener) mMainFragment);
    }

    private void unBoundDevice(SingleDevice singleDevice) {
        MainActivity mainActivity = (MainActivity) getActivity();
        mainActivity.showProgressDialog(getString(R.string.group_device_removing) + singleDevice.getName());
        List<Integer> groups = new ArrayList<>();
        groups.addAll(singleDevice.getGroupMembership());
        if (groups.indexOf(groupId) != -1) {
            groups.remove(groups.indexOf(groupId));
            mController.setSelectedDeviceId(singleDevice.getDeviceId());
            mController.setDeviceGroups(groups, (GroupListener) mMainFragment);
        }
    }

    @Override
    public void groupsUpdated(int deviceId, boolean success, String msg) {
        if (!success) {
            mController.deleteModel(groupId, deviceId);
        }
        resetUI();
        MainActivity mainActivity = (MainActivity) getActivity();
        mainActivity.hideProgressDialog();
    }
}
